from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from modules.system.schemas.dict_schemas import DictTypeCreate, DictTypeUpdate
from modules.system.params.dict_params import DictTypeQuery
from modules.system.services.dict_service import DictService
from modules.system.vos.dict_vo import DictTypeResponse, DictTypeListResponse
from modules.system.vos.dict_item_vo import DictItemResponse
from core.pagination import DependsPagination

router = APIRouter()


@router.post("/create", response_model=ApiResponse[DictTypeResponse], summary="创建字典类型")
async def create_dict_type(payload: DictTypeCreate, db: AsyncSession = Depends(get_db)):
    t = await DictService.create_type(db, payload)
    return api_success(DictTypeResponse.model_validate(t), msg="创建成功")


@router.post(
    "/list", 
    response_model=ApiResponse[DictTypeListResponse], 
    summary="获取字典类型列表",
    dependencies=[DependsPagination]
)
async def list_dict_types(query_params: DictTypeQuery, db: AsyncSession = Depends(get_db)):
    result = await DictService.get_types_with_pagination(db, query_params)
    return api_success(data=result,msg="获取成功")


@router.put("/{type_id}", response_model=ApiResponse[DictTypeResponse], summary="更新字典类型")
async def update_dict_type(type_id: int, payload: DictTypeUpdate, db: AsyncSession = Depends(get_db)):
    t = await DictService.update_type(db, type_id, payload)
    return api_success(DictTypeResponse.model_validate(t), msg="更新成功")


@router.delete("/{type_id}", response_model=ApiResponse[dict], summary="删除字典类型")
async def delete_dict_type(type_id: int, db: AsyncSession = Depends(get_db)):
    await DictService.delete_type(db, type_id)
    return api_success({"message": f"字典类型ID {type_id} 删除成功"}, msg="删除成功")


@router.post("/cache", response_model=ApiResponse[dict], summary="批量获取字典缓存")
async def get_dict_cache(payload: dict, db: AsyncSession = Depends(get_db)):
    """
    请求体示例：
    {
        "types": ["gender", "status", "dept_type"]
    }
    返回结构：
    {
        "gender": [DictItemResponse...],
        "status": [DictItemResponse...],
        "dept_type": [DictItemResponse...]
    }
    当不传 types 或为空数组时，返回所有类型的字典项。
    """
    type_codes = payload.get("types")
    grouped = await DictService.get_items_grouped_by_types(db, type_codes if type_codes else None)

    # 将 ORM 对象序列化为响应 VO
    serialized = {k: [DictItemResponse.model_validate(i) for i in v] for k, v in grouped.items()}
    return api_success(serialized, msg="获取成功")